/*
* 授权服务主要是做 颁发令牌；资源服务做的是验证令牌
* 每个资源服务里面都配置一个资源校验服务就可以了
*
* 一般资源服务跟授权服务是分开的
* */
package cn.learn.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * 资源服务配置
 * 启动全局权限标签 @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
 * OAuth2AuthenticationProcessingFilter
 * https://blog.csdn.net/qq_22178703/article/details/101367159
 *
 * @author huangyezhan
 * @date 2020年2月28日17:37:46
 */
@Slf4j
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource
    private TokenStore tokenStore;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                //本资源id
                .resourceId("order")
                //本地解析token
                .tokenStore(tokenStore)
                //验证令牌的服务
                //.tokenServices(tokenServices())
                .stateless(true)
        ;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        log.info("资源服务器校验");
        http//.addFilterBefore(myOAuth2AuthenticationProcessingFilter, AbstractPreAuthenticatedProcessingFilter.class)
                .authorizeRequests()

                .antMatchers("/order/testOrder").hasAuthority("test")
                .antMatchers("/order/placeOrder").hasAuthority("place")
                .antMatchers("/order/cancelOrder").hasAuthority("cancel")
                .antMatchers("/order/deleteOrder").hasAuthority("delete")

                .antMatchers("/**").access("#oauth2.hasScope('all')")
                .anyRequest().authenticated()
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
    }


    /**
     * 资源服务令牌解析服务，一般有两种：
     * 本地 DefaultTokenServices
     * 远程 RemoteTokenServices
     */
   /* @Bean
    public ResourceServerTokenServices tokenServices(){
        RemoteTokenServices service = new RemoteTokenServices();
        service.setCheckTokenEndpointUrl("http://localhost:8087/oauth/check_token");
        service.setClientId("user_1");
        service.setClientSecret("123456");
        return service;
    }*/

}
